package cn.bdqn.pn.service.commodity.CommodityServiceImpl;

import cn.bdqn.pn.pojo.commodity.Sku;
import cn.bdqn.pn.reposity.commodity.SkuReposity;
import cn.bdqn.pn.service.commodity.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service("skuService")
public class SkuServiceImpl implements SkuService {
    @Autowired
    private SkuReposity skuReposity;
    @Override
    public boolean addSku(Sku sku) {
        Sku addSku=skuReposity.save(sku);
        if (addSku!=null){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public boolean updateSkuStatus(Integer skuId) {
        System.out.println("+++++++++++++++++++++>>>    "+skuId+"   <<<<++++++++++++++++++++");
        Sku sku=skuReposity.findOne(skuId);

        sku.setSkuStatus(2);
        Sku sku1=skuReposity.save(sku);
        if(sku1!=null){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public List<Sku> getSkuListByCommodityId(Integer commodityId) {
        List<Sku> resultList = null;
        Specification<Sku> querySpecifi = new Specification<Sku>() {
            @Override
            public Predicate toPredicate(Root<Sku> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(criteriaBuilder.equal(root.get("commdityId").as(Integer.class),commodityId));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        resultList =  this.skuReposity.findAll(querySpecifi);
        return resultList;
    }

    @Override
    public Sku getSkuById(Integer SkuId) {
        return skuReposity.findOne(SkuId);
    }
}
